#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is part of KeyExtracta
# <http://code.google.com/p/keyextracta/>.
#
# KeyExtracta is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# KeyExtracta is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with KeyExtracta.  If not, see <http://www.gnu.org/licenses/>.

import _winreg as wr
import platform

def SubKeys(key):
  """Parse through sub keys"""
  i = 0
  while True:
    try:
      subkey = wr.EnumKey(key, i)
      yield subkey
    except WindowsError: # [Error 259] No more data is available
      break
    i += 1
        
def KeyValues(key):
  """Parse through key values"""
  i = 0
  while True:
    try:
      value = wr.EnumValue(key, i)
      yield value
    except WindowsError: # [Error 259] No more data is available
      break
    i += 1
    
def isOS64bit():
  """
  Determine if operating system is 64 bit
  http://stackoverflow.com/a/12578715/1061279
  """
  return platform.machine().endswith('64')

def getOSFlag():
  """
  Determine if OS is 64 bit or not.  If it is, pass KEY_WOW64_64KEY to read
  64bit section of registry.
  """
  if isOS64bit():
    return wr.KEY_WOW64_64KEY
  else:
    return wr.KEY_WOW64_32KEY

def getOSFlagList():
  """Get list of OS flags.  Return [wr.KEY_WOW64_32KEY] by default"""
  fl = [wr.KEY_WOW64_32KEY]
  if isOS64bit():
    fl.append(wr.KEY_WOW64_64KEY)
  return fl

def chunks(l, n):
  """Yield successive n-sized chunks from l."""
  for i in xrange(0, len(l), n):
    yield l[i:i+n]
    
def getComputerName():
  """Get the computer name from the Windows registry"""
  reg_root = r'System\CurrentControlSet\Control\ComputerName\ComputerName'
  flag = getOSFlag()
  ms_root = wr.OpenKey(wr.HKEY_LOCAL_MACHINE, reg_root, 0,
      wr.KEY_READ | flag)
  for keyvalue in KeyValues(ms_root):
    if keyvalue[0].lower() == 'computername':
      return keyvalue[1]  